package com.pinyoumei.app.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.bean.AccountBean;
import com.pinyoumei.app.bean.RegisterBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.AppManager;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.StatusBarUtils;
import com.pinyoumei.app.view.LoadingDailog;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import java.util.HashMap;
import java.util.Map;

import io.realm.Realm;


/**
 * 添加账号
 */
public class AddAccountActivity extends AppCompatActivity implements View.OnClickListener{
    private EditText edittext_account;
    private EditText edittext_password;
    private ImageView image_delete;
    private ImageView image_delete_password;
    private RelativeLayout relative_login;
    private LoadingDailog loadingDailog;

    protected AppManager appManager = AppManager.getInstance();
    private Gson gson;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
        StatusBarUtils.setRootViewFitsSystemWindows(this,true);
        //设置状态栏透明
        StatusBarUtils.setTranslucentStatus(this);
        //一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
        //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
        if (!StatusBarUtils.setStatusBarDarkTheme(this, true)){
            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
            //这样半透明+白=灰, 状态栏的文字能看得清
            StatusBarUtils.setStatusBarColor(this,0x55000000);
        }
        // 添加activity 到栈
        appManager.addActivity(this);

        gson = new Gson();
        LoadingDailog.Builder builder = new LoadingDailog.Builder(this)
                .setMessage("加载中...")
                .setCancelable(true);
        loadingDailog = builder.create();

        setContentView(R.layout.activity_layout_addaccount);
        initwidget();

        edittext_account.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                 if(s.length()>0){
                     image_delete.setVisibility(View.VISIBLE);
                 }else{
                     image_delete.setVisibility(View.GONE);
                 }
            }
        });
        edittext_password.addTextChangedListener(new TextWatcher(){
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s){
                if(s.length()>0){
                    image_delete_password.setVisibility(View.VISIBLE);
                }else{
                    image_delete_password.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.relative_finish:
                finish();
                break;
            case R.id.image_delete:
                edittext_account.setText("");
                break;
            case R.id.image_delete_password:
                edittext_password.setText("");
                break;
            case R.id.relative_login://登录
                login(edittext_account.getText().toString().trim(),edittext_password.getText().toString().trim(), 1);//安卓类型
                break;
        }
    }
    private void initwidget(){
        image_delete = findViewById(R.id.image_delete);
        image_delete.setOnClickListener(this);
        image_delete.setVisibility(View.GONE);
        image_delete_password = findViewById(R.id.image_delete_password);
        image_delete_password.setOnClickListener(this);
        image_delete_password.setVisibility(View.GONE);
        edittext_account = findViewById(R.id.edittext_account);
        edittext_password = findViewById(R.id.edittext_password);
        relative_login = findViewById(R.id.relative_login);
        relative_login.setOnClickListener(this);

    }
    //添加账号登录请求

    private void login(String user_phone,String user_pwd,int app_type) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_phone", user_phone);
        map.put("user_pwd", user_pwd);
        map.put("app_type", app_type);

        OkGo.<String>post(Constants.LOGIN_CHECK)
                .params("user_phone", user_phone)
                .params("user_pwd", user_pwd)
                .params("app_type", app_type)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        RegisterBean registerBean = gson.fromJson(response.body(), RegisterBean.class);

                        if (registerBean.getCode() >= 0) {

                            //保存登录账号的信息的实体类到本地数据库
                            Realm realm = Realm.getDefaultInstance();
                            AccountBean accountBean = new AccountBean();
                            accountBean.setName(registerBean.getResult().getUser_name());
                            accountBean.setPhone(registerBean.getResult().getUser_phone());
                            accountBean.setPassword(user_pwd);
                            accountBean.setApp_user_id(registerBean.getResult().getUser_id());
                            accountBean.setUser_head_image(registerBean.getResult().getUser_head_img());
                            realm.executeTransaction(new Realm.Transaction() {
                                @Override
                                public void execute(Realm realm) {
                                    realm.copyToRealmOrUpdate(accountBean);
                                    //进入主界面
                                    SPUtils.saveAppUserId(AddAccountActivity.this,registerBean.getResult().getUser_id());

                                    SPUtils.saveUserPhone(AddAccountActivity.this,registerBean.getResult().getUser_phone());

                                    finish();
                                    appManager.killAllActivity();
                                    startActivity(new Intent(AddAccountActivity.this,MainUIActivity.class));

                                }
                            });




                        } else {
                            Toast.makeText(AddAccountActivity.this, registerBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });


    }
}
